package com.jhws.core.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.jhws.common.Page;
import com.jhws.core.spring.PageContext;

@Transactional
public class BaseDao extends SuperBaseDaoImpl{
	
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public JdbcTemplate j() {
		return DaoTemplateContext.getJdbcTemplate();
	}
	
	public HibernateTemplate h() {
		return DaoTemplateContext.getHibernateTemplate();
	}

	
	public Page queryPage(String sql, Class<?> clazz){
		Page page = PageContext.getPage(true);
		if(CollectionUtils.isNotEmpty(page.getList())){
			throw new IllegalStateException("分页查询只能做一次");
		}
		
		Query query = h().getSessionFactory().getCurrentSession().createSQLQuery(sql);
		query.setFirstResult(page.getStart());
		query.setMaxResults(page.getNumberPerPage());
		if(clazz != Map.class){
			query.setResultTransformer(new AliasToBeanResultTransformer(clazz));
		}else{
			query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		}
		List<?> list = query.list();
		page.setList(list);

		/* 过滤排序语句 */
		sql = sql.replaceAll("order by (.*)[ ]+(.*)","");

		page.setTotalNumber(j().queryForObject("select count(*) from   (" +sql+") __t", Integer.class));
		return page;
	}

	/**
	 * 使用hibernate hql查询分页数据, 直接返回一个包含列表和总数据条目的Map结构
	 * @param hql
	 * @return
	 */
	public Map queryPage(String hql){
		Page page = PageContext.getPage(true);
		if(CollectionUtils.isNotEmpty(page.getList())){
			throw new IllegalStateException("分页查询只能做一次");
		}

		Query query = h().getSessionFactory().getCurrentSession().createQuery(hql);
		query.setFirstResult(page.getStart());
		query.setMaxResults(page.getNumberPerPage());
		List<?> list = query.list();
		page.setList(list);


		page.setTotalNumber(getCountByHql(getCountQuery(hql)).intValue());
		Map retMap = new HashMap();
		retMap.put("size",page.getTotalNumber());
		retMap.put("list",page.getList());
		return retMap;
	}

}
